//
//  RequestService+Home.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/27.
//

import UIKit
import Alamofire
import Swime
extension RequestService {
    //dataType 1: 首页 2：技能中心
    func checkKeyword(message:String, completeClosure: ((Bool) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/infos/words",
                        method: .post,
                        parameters: ["message":message, "sign":sign, "timestamp": time], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any], let checkCode = result["checkCode"] as? String else {
                    completeClosure?(false)
                    return
                }
                if checkCode.contains("no") {
                    completeClosure?(false)
                }else {
                    completeClosure?(true)
                }
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    //dataType 1: 首页 2：技能中心
    func chat_v1(message: String, dataType: Int, dataId: String, completeClosure: ((AIStreamMessage?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId": system_id,
                                                               "timestamp": time])
        let request = session.streamRequest("\(apiHost)/api/infos/chat_v3",
                                            method: .post,
                                            parameters: ["message": message,
                                                         "sign": sign,
                                                         "timestamp": time,
                                                         "dataType": "\(dataType)",
                                                         "dataId": dataId])
        request.validate() // 可选的数据验证
        var dataStr = ""
        request.responseStream { stream in
            switch stream.event {
            case let .stream(result):
                switch result {
                case let .success(data):
                    if let responseString = String(data: data, encoding: .utf8) {
                        let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                        if let jsonDic = JSON as? [String: Any],
                           let current = jsonDic["code"] as? String, current != "200" {
                            GlobalRx.requestErrSubject.onNext(ReqServerCode(code: Int(current) ?? 0, msg: jsonDic["msg"] as? String))
                            completeClosure?(nil) // 处理不了的情况下，传空
                        }else {
                            dataStr = dataStr + responseString
                        }
                    } else {
                        completeClosure?(nil) // 处理不了的情况下，传空
                    }
                case let .failure(error):
                    failureClosure?(error.localizedDescription)
                    XLog.d("chat_v1", "stream error", error)
                }
            case .complete:
                if dataStr.count > 0 {
                    let model = AIStreamMessage.parseMessageFromResponse(response: dataStr)
                    completeClosure?(model)
                }
                // 处理流结束的情况
                // 这里可以执行一些清理工作或者提示操作完成
                break
            }
        }
    }
    
    func chat_v2(message: String, dataType: Int, dataId: String, completeClosure: ((AIStreamMessage?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId": system_id,
                                                               "timestamp": time])
        let request = session.streamRequest("\(apiHost)/api/infos/chat_v4",
                                            method: .post,
                                            parameters: ["message": message,
                                                         "sign": sign,
                                                         "timestamp": time,
                                                         "dataType": "\(dataType)",
                                                         "dataId": dataId])
        
        
        
        request.validate() // 可选的数据验证
        var dataStr = ""
        request.responseStream { stream in
            switch stream.event {
            case let .stream(result):
                //                self.statRequest(result)
                switch result {
                case let .success(data):
                    if let responseString = String(data: data, encoding: .utf8) {
                        let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                        if let jsonDic = JSON as? [String: Any],
                           let current = jsonDic["code"] as? String, current != "200" {
                            GlobalRx.requestErrSubject.onNext(ReqServerCode(code: Int(current) ?? 0, msg: jsonDic["msg"] as? String))
                            completeClosure?(nil) // 处理不了的情况下，传空
                        }else {
                            dataStr = dataStr + responseString
                        }
                    } else {
                        completeClosure?(nil) // 处理不了的情况下，传空
                    }
                case let .failure(error):
                    failureClosure?(error.localizedDescription)
                    XLog.d("chat_v1", "stream error", error)
                }
            case .complete:
                if dataStr.count > 0 {
                    let model = AIStreamMessage.parseMessageFromResponse(response: dataStr)
                    completeClosure?(model)
                }
                // 处理流结束的情况
                // 这里可以执行一些清理工作或者提示操作完成
                break
            }
        }
    }
    
    
    
    func homeVideoList(page:Int, completeClosure: (([VideoHistoryModel]?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId": system_id,
                                                               "timestamp": time,
                                                               "page":"\(page)"])
        session.request("\(apiHost)/api/novel/list",
                        method: .post,
                        parameters: ["page":"\(page)", "sign":sign, "timestamp": time], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any],
                      let content = result["content"] as? [[String: Any]],
                      let models = [VideoHistoryModel].deserialize(from: content) else { return }
                completeClosure?(models.compactMap { $0 })
                
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func homeDrawList(page:Int, completeClosure: (([PaintImageDataModel]?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId": system_id,
                                                               "timestamp": time,
                                                               "page":"\(page)"])
        session.request("\(apiHost)/api/image/result_list",
                        method: .post,
                        parameters: ["page":"\(page)", "sign":sign, "timestamp": time], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any],
                      let content = result["content"] as? [[String: Any]],
                      let models = [PaintImageDataModel].deserialize(from: content) else { return }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
}

